package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.config.SpringConfig;
import com.atguigu.spring5.dao.UserDao;
import com.atguigu.spring5.dao.UserDaoImpl2;
import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    //用注解的方式创建bean， 1.xml开启包扫描  2.类上加@Service注解
    @Test
    public void testAnnotation() {
        ApplicationContext context
                = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService.getName());
    }

    //调用add()方法，检验属性userDao的自动装配效果
    @Test
    public void testDIProperty() {
        ApplicationContext context
                = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

    //配置类@Configuration，取代xml文件
    @Test
    public void testConfigClass() {
        //加载配置类
        ApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }

    //测试通过@Bean注解来注入对象
    @Test
    public void testBeanAnno() {
        //加载配置类
        ApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        for(String s : context.getBeanDefinitionNames())
            System.out.println(s);

        UserDao userDao = context.getBean("getUserDao", UserDao.class);
        userDao.add();
    }

}
